<?php

namespace app\api\model\hotel;

use app\api\model\UserCoupon;
use app\common\model\User;
use think\Model;
use traits\model\SoftDelete;


class HotelOrder extends Model
{

    // 订单创建
    const ORDER_CREATE = 0;

    // 订单待入住
    const ORDER_WAIT_CHECKIN = 1;

    //已完成
    const ORDER_COMPLETE = 10;

    //已取消
    const ORDER_CLOSE = -1;

    //售后
    const ORDER_REFUND = 4;

    public $order_status = [
        self::ORDER_CREATE           => [
            'status'          => self::ORDER_CREATE,
            'name'            => '待支付',
        ],
        self::ORDER_WAIT_CHECKIN           => [
            'status'          => self::ORDER_WAIT_CHECKIN,
            'name'            => '待入住',
        ],
        self::ORDER_COMPLETE           => [
            'status'          => self::ORDER_COMPLETE,
            'name'            => '已完成',
        ],
        self::ORDER_CLOSE           => [
            'status'          => self::ORDER_CLOSE,
            'name'            => '已取消',
        ],
        self::ORDER_CLOSE           => [
            'status'          => self::ORDER_CLOSE,
            'name'            => '已取消',
        ],
        self::ORDER_REFUND           => [
            'status'          => self::ORDER_REFUND,
            'name'            => '售后',
        ],
    ];


    use SoftDelete;


    // 表名
    protected $name = 'hotel_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [

    ];


    //用户订单列表
    public function getUserOrderList($data)
    {
        $order_status = $data['order_status'];

        $where = ['ho.user_id'=>$data['user_id']];

        switch ( $order_status ) {
            case "waitpay"://待支付
                $where['ho.order_status'] = 0;
                break;
            case "waitcheckin"://待入住
                $where['ho.order_status'] = 1;
                break;
            case "complete"://已完成
                $where['ho.order_status'] = 10;
                break;
            case "refund"://售后
                $where['ho.order_status'] = 4;
                break;
        }

        $list = HotelOrder::alias('ho')
            ->where($where)
            ->field('ho.order_id,ho.order_no,ho.hotel_id,ho.hotel_name,ho.room_id,ho.room_image,ho.room_name,ho.checkin_date
            ,ho.leave_date,ho.order_status,ho.order_status_name,ho.order_money,ho.pay_money,ho.createtime')
            ->order('ho.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;

        foreach ($list as $k=>$v){
            $list[$k]['auto_close'] = $v['createtime'] + $auto_close-time();
        }

        return $list;
    }

    //用户订单详情
    public function getUserOrderInfo($order_id,$user_id,$lat,$lng)
    {
        $info = HotelOrder::where(['order_id'=>$order_id,'user_id'=>$user_id])->find();
        if (!$info)throw new \Exception('不是当前用户订单');

        $room_info = HotelRoom::alias('r')
            ->join('hotel h','r.hotel_id = h.hotel_id')
            ->where(['r.room_id'=>$info['room_id']])
            ->field('r.room_id,r.hotel_id,r.room_name,r.image,r.label,r.price,h.address,h.lat,h.lng,h.hotel_name,h.refund_explain')
            ->find();

        $info['room_info'] = $room_info;
        if ($room_info[ 'lng' ] && $room_info[ 'lat' ]&&$lng&&$lat) {
            $distance = getDistance((float) $room_info[ 'lng' ], (float) $room_info[ 'lat' ], (float) $lng, (float) $lat);
            $info[ 'distance' ] = round($distance / 1000,1);
        } else {
            $info[ 'distance' ] = 0;
        }

        $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;

        $info['auto_close'] = $info['createtime'] + $auto_close-time();
        return $info;
    }


    public function notify($out_trade_no,$paytype)
    {
        $order = HotelOrder::get(['order_no' => $out_trade_no]);
        if ($order->pay_status==0){
            $order->pay_type = $paytype;
            $order->pay_status = 1;
            $order->pay_time = time();
            $order->setAttr('order_status',1);
            $order->order_status_name = $this->order_status[self::ORDER_WAIT_CHECKIN]['name'];
            $order->save();
            if ($order->award_score){
                User::score($order->award_score,$order->user_id,'消费奖励积分,订单编号:'. $order->order_no);
            }
        }
        return true;
    }

    //订单取消
    public function orderCancel($order_id)
    {
        $info = HotelOrder::where(['order_id'=>$order_id])->find();

        if ($info['order_status']==-1)return true;

        $data = [
            'order_status'=>self::ORDER_CLOSE,
            'order_status_name'=>$this->order_status[self::ORDER_CLOSE]["name"],
            'cancel_time'=>time()
        ];

        if ($info['coupon_id']){
            $coupon_model = new UserCoupon();
            $coupon_model->resetUserCoupon($info['coupon_id']);
        }

        if ($info['use_score']<0&&$info['order_type']==3){
            User::score($info['use_score'],$info['user_id'],$info['order_no'].'订单关闭退回');
        }

        $res = HotelOrder::where(['order_id'=>$order_id])->update($data);

        return $res;
    }

    //订单售后
    public function orderRefund($order_id)
    {
        $info = HotelOrder::where(['order_id'=>$order_id])->find();

        if ($info['order_status']==4)return true;

        $data = [
            'order_status'=>self::ORDER_REFUND,
            'order_status_name'=>'退款中',
            'salestate'=>1,
            'refund_time'=>time()
        ];

        $res = HotelOrder::where(['order_id'=>$order_id])->update($data);

        return $res;
    }

    //订单取消售后
    public function orderCancelRefund($order_id)
    {
        $info = HotelOrder::where(['order_id'=>$order_id])->find();

        if ($info['order_status']==4)return true;

        $data = [
            'order_status'=>self::ORDER_WAIT_CHECKIN,
            'order_status_name'=>$this->order_status[self::ORDER_WAIT_CHECKIN]['name'],
            'salestate'=>2
        ];

        $res = HotelOrder::where(['order_id'=>$order_id])->update($data);

        return $res;
    }
}
